using System;
using System.ComponentModel;

namespace Td.Additional.ComponentModel
{
    /// <summary>
    /// Expandable converter.
    /// </summary>
    class PropertySetConverter : ExpandableObjectConverter
    {
        #region ExpandableObjectConverter

        /// <summary>
        /// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
        /// <param name="sourceType">A <see cref="T:System.Type"/> that represents the type you want to convert from.</param>
        /// <returns>
        /// true if this converter can perform the conversion; otherwise, false.
        /// </returns>
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(String))
                return true;
            return base.CanConvertFrom(context, sourceType);
        }

        /// <summary>
        /// Returns whether this converter can convert the object to the specified type, using the specified context.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
        /// <param name="destinationType">A <see cref="T:System.Type"/> that represents the type you want to convert to.</param>
        /// <returns>
        /// true if this converter can perform the conversion; otherwise, false.
        /// </returns>
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(String))
                return true;
            return base.CanConvertTo(context, destinationType);
        }

        /// <summary>
        /// Converts the given object to the type of this converter, using the specified context and culture information.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
        /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture.</param>
        /// <param name="value">The <see cref="T:System.Object"/> to convert.</param>
        /// <returns>
        /// An <see cref="T:System.Object"/> that represents the converted value.
        /// </returns>
        /// <exception cref="T:System.NotSupportedException">
        /// The conversion cannot be performed.
        /// </exception>
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is String)
            {
                try
                {
                    PropertySet result = new PropertySet();
                    String[] properties = (value as String).Split(';');
                    int index = -1;
                    foreach (String prop in properties)
                    {
                        index = prop.IndexOf(',');// Category/Name splitter
                        String category = prop.Substring(1, index - 1);
                        String name = prop.Substring(index + 1, prop.IndexOf(']') - (index + 1));
                        index = prop.IndexOf('(');// Type
                        Type type = Type.GetType(prop.Substring(index + 1, prop.IndexOf(')') - (index + 1)));
                        index = prop.IndexOf('=');// Value
                        Property property = new Property(category, name, type, Convert.ChangeType(prop.Substring(index + 1), type));
                        result.Add(property);
                    }
                    return result;
                }
                catch (Exception ex)
                {
                    throw new ArgumentException(
                        String.Format("Cannot convert {0} to PropertySet", value.GetType().ToString()),
                        ex);
                }
            }
            return base.ConvertFrom(context, culture, value);
        }

        /// <summary>
        /// Converts the given value object to the specified type, using the specified context and culture information.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
        /// <param name="culture">A <see cref="T:System.Globalization.CultureInfo"/>. If null is passed, the current culture is assumed.</param>
        /// <param name="value">The <see cref="T:System.Object"/> to convert.</param>
        /// <param name="destinationType">The <see cref="T:System.Type"/> to convert the <paramref name="value"/> parameter to.</param>
        /// <returns>
        /// An <see cref="T:System.Object"/> that represents the converted value.
        /// </returns>
        /// <exception cref="T:System.ArgumentNullException">
        /// The <paramref name="destinationType"/> parameter is null.
        /// </exception>
        /// <exception cref="T:System.NotSupportedException">
        /// The conversion cannot be performed.
        /// </exception>
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(String) && value is PropertySet)
            {
                try
                {
                    String result = String.Empty;
                    foreach (Property property in (value as PropertySet).GetProperties())
                    {
                        if (!String.IsNullOrEmpty(result))
                            result += ";";
                        result += "[" + property.Category + "," + property.Name + "]=";
                        result += "(" + property.PropertyType.ToString() + ")";
                        result += property.ToString();
                    }
                }
                catch (Exception ex)
                {
                    throw new ArgumentException(
                        String.Format("Cannot convert {0} to {1}", value.GetType().ToString(), destinationType.ToString()), 
                        ex);
                }
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }

        #endregion
    }
}